package net.kmtarena.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Random;

import net.kmtarena.db.Db;
import net.kmtarena.util.Md5;
import net.kmtarena.util.SendMail;
import net.kmtarena.vo.User;

/**
 * 用户相关数据库操作类
 * 
 * @author Funnyking funnyking@139.com by 2012-11-27
 */
public class UserDao {
	PreparedStatement ps = null;
	Connection conn = null;
	ResultSet rs = null;

	/**
	 * 判断是否登陆成功
	 * 
	 * @param User
	 *            用户对象
	 * @return User 不为null表示登陆成功
	 */
	public User login(User u) {
		String sql = "select * from user where name=? and password=?";
		int code = 0;
		try {
			conn = Db.getConn();
			// 查询code加权因子
			UserDao dao = new UserDao();
			code = dao.getCode(u);
			// 如果没有查询到，则直接返回空
			if (code == 0) {
				rs.close();
				ps.close();
				conn.close();
				return null;
			}
			// 查询用户名密码是否正确d
			ps = null;
			ps = conn.prepareStatement(sql);
			ps.setString(1, u.getName());
			// 密码要加密处理后进行对比
			ps.setString(2, Md5.getPass(u.getPassword(), code));
			rs = ps.executeQuery();
			// 查询后赋空，如果没有查询到则直接返回null
			u = null;
			if (rs.next()) {
				u.setId(rs.getInt("Id"));
				u.setName(rs.getString("name"));
				u.setPassword(rs.getString("password"));
				u.setGender(rs.getInt("gender"));
				u.setPosionid(rs.getInt("posionid"));
				//TODO 此处需要调用通过ID获取职位信息方法
				u.setPhone(rs.getString("phone"));
				u.setTel(rs.getString("tel"));
				u.setCode(rs.getInt("code"));
				u.setRegTime(rs.getString("regTime"));
				u.setRegIP(rs.getString("retIP"));
				u.setRegMac(rs.getString("regMAC"));
				u.setLastTime(rs.getString("lastTime"));
				u.setState(rs.getInt("state"));
				u.setCompanyId(rs.getInt("CompanyId"));
				//TODO 此处需要调用通过ID获取公司信息方法
			}
		} catch (SQLException e) {
			SendMail sm = new SendMail();
			sm.setAddress("funnyking@139.com",
					"【教学系统】用户登陆错误 UserDao.login() error!");
			sm.send("net.kmtarena.dao.UserDao.login() error!");
		} finally {
			Db.getCatch("用户登陆错误 UserDao.login()",
					"net.kmtarena.dao.UserDao.login()", conn, ps, rs);
		}
		return u;
	}
	
	/**
	 * 通过用户ID设置用户最后一次登陆时间（登录时需调用此方法）
	 * @param User 用户id
	 * @return boolean 返回false表示更新失败
	 */
	public boolean updLastTime(User u){
		boolean b = false;
		String sql = "update user set lastTime=? where id=?";
		conn = Db.getConn();
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, Long.toString(Calendar.getInstance()
					.getTimeInMillis()));
			ps.setInt(2, u.getId());
			b = ps.execute();
		} catch (SQLException e) {
			SendMail sm = new SendMail();
			sm.setAddress("funnyking@139.com",
					"【教学系统】最后一次登陆时间更新错误 UserDao.updLastTime() error!");
			sm.send("net.kmtarena.dao.UserDao.updLastTime() error!");
		}finally {
			Db.getCatch("最后一次登陆时间更新错误 UserDao.updLastTime()",
					"net.kmtarena.dao.UserDao.updLastTime()", conn, ps);
		}
		return b;
	}

	/**
	 * 查询已有的加权因子
	 * 
	 * @param u
	 *            用户名
	 * @return int code加权因子
	 */
	public int getCode(User u) {
		String codeStr = "select code from user where name=?";
		int code = 0;
		try {
			ps = conn.prepareStatement(codeStr);
			ps.setString(1, u.getName());
			rs = ps.executeQuery();
			if (rs.next()) {
				code = rs.getInt("code");
			}
		} catch (SQLException e) {
			SendMail sm = new SendMail();
			sm.setAddress("funnyking@139.com",
					"【教学系统】获取加权因子 UserDao.getCode() error!");
			sm.send("net.kmtarena.dao.UserDao.getCode() error!");
		} finally {
			Db.getCatch("获取加权因子 UserDao.getCode()",
					"net.kmtarena.dao.UserDao.getCode()", conn, ps, rs);
		}
		return code;
	}

	/**
	 * 用户添加
	 * 
	 * @param u
	 *            用户对象
	 * @return boolean true表示添加成功
	 */
	public boolean addUser(User u) {
		boolean b = false;
		String sql = "insert into user (name,password,gender,posionid,phone,tel,code,regTime,regIP,regMAC,lastTime,state,companyId) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
		// 生成四位随机码用于加密
		UserDao dao = new UserDao();
		int code = dao.getCode();
		try {
			conn = Db.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, u.getName());
			// 此处密码要进行加密处理
			ps.setString(2, Md5.getPass(u.getPassword(), code));
			ps.setInt(3, u.getGender());
			ps.setInt(4, u.getPosionid());
			ps.setString(5, u.getPhone());
			ps.setString(6, u.getTel());
			ps.setInt(7, code);
			ps.setString(8, Long.toString(Calendar.getInstance()
					.getTimeInMillis()));
			ps.setString(9, u.getRegIP());
			ps.setString(10, u.getRegMac());
			ps.setString(11, Long.toString(Calendar.getInstance()
					.getTimeInMillis()));
			ps.setInt(12, 0);
			ps.setInt(13, u.getCompanyId());
			if (ps.executeUpdate() > 0) {
				b = true;
			}
		} catch (SQLException e) {
			System.out.println(e.toString());
			SendMail sm = new SendMail();
			sm.setAddress("funnyking@139.com",
					"【教学系统】用户添加错误 UserDao.addUser() error!");
			sm.send("net.kmtarena.dao.UserDao.addUser() error!");
		} finally {
			Db.getCatch("用户添加错误UserDao.addUser()",
					"net.kmtarena.dao.UserDao.addUser() ", conn, ps);
		}
		return b;
	}

	/**
	 * 修改用户密码
	 * 
	 * @param pwd
	 *            修改后的密码
	 * @return boolean true表示成功
	 */
	public boolean updatePwd(String pwd) {
		return false;
	}

	/**
	 * 生成四位随机码
	 * 
	 * @return int 四位随机码
	 */
	public int getCode() {
		Random rand = new Random();
		return Integer.parseInt("" + rand.nextInt(10) + rand.nextInt(10)
				+ rand.nextInt(10) + rand.nextInt(10));
	}

	/**
	 * TODO 测试方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

	}
}
